<template>
  <div class="user-warp">
    <div class="user-content">
      <div class="user-center">
        <div class="user-title">账号设置</div>
        <div class="user-detil">基本信息</div>
        <div class="user-edit">
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="edit-center" @click="openUpdateNameDialog('updateAvatar')">
                  <template v-if="userImg">
                    <img v-lazy="userImg" alt="头像" class="avatar-img" />
                  </template>
                  <template v-else>
                    <t-avatar class="avatar-img">{{ userNameAvatar }}</t-avatar>
                  </template>
                </div>
                <div class="avatar-content">头像</div>
              </div>
              <div class="avatar-warning">仅支持 1M 以内的 .JPG .PNG 图片格式</div>
            </div>
            <button class="avatar-btn" @click="openUpdateNameDialog('updateAvatar')">
              上传头像
            </button>
          </div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">昵称</div>
              </div>
              <div class="avatar-warning">{{ nickName }}</div>
            </div>
            <button class="avatar-btn" @click="openUpdateNameDialog('updateName')">修改昵称</button>
          </div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">生日</div>
              </div>
              <div class="avatar-warning">
                {{ userBirthday }}
              </div>
            </div>
            <button class="avatar-btn" @click="openUpdateNameDialog('updateBirthday')">
              修改生日
            </button>
          </div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">UID</div>
              </div>
              <div class="avatar-warning">{{ userMypromotionCode }}</div>
            </div>
            <button class="avatar-btn" @click="copyToClipboard(getUrl(userMypromotionCode))">
              复制邀请链接
            </button>
          </div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">邮箱</div>
              </div>
              <div class="avatar-warning" v-if="!userEmail">
                <v-icon
                  name="weibangding"
                  color="rgb(0, 157, 255)"
                  width="14px"
                  height="14px"
                  style="margin-right: 4px"
                />未绑定
              </div>
              <div class="avatar-warning" v-else>{{ userEmail }}</div>
            </div>
            <button class="avatar-btn" @click="openUpdateNameDialog('updateEmail')">
              {{ userEmail ? '修改邮箱' : '立即绑定' }}
            </button>
          </div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">手机号</div>
              </div>
              <div class="avatar-warning" v-if="!userMobile">
                <v-icon
                  name="weibangding"
                  color="rgb(0, 157, 255)"
                  width="14px"
                  height="14px"
                  style="margin-right: 4px"
                />未绑定
              </div>
              <div class="avatar-warning" v-else>{{ userMobile }}</div>
            </div>
            <button class="avatar-btn" @click="openUpdateNameDialog('updateMobile')">
              {{ userMobile ? '修改手机' : '立即绑定' }}
            </button>
          </div>
          <div class="user-detil">第三方账号</div>
          <div class="user-info-center">
            <div class="user-setting">
              <div class="edit-item">
                <div class="avatar-content">微信</div>
              </div>
              <div class="avatar-warning" v-if="!userWStatus">
                <v-icon
                  name="weibangding"
                  color="rgb(0, 157, 255)"
                  width="14px"
                  height="14px"
                  style="margin-right: 4px"
                />未绑定
              </div>
              <div class="avatar-warning" v-else>{{ userWStatus }}</div>
            </div>
            <button
              class="avatar-btn"
              @click="openUpdateNameDialog('updateWechat')"
              v-bind:disabled="wxButton"
            >
              {{ userWStatus ? '解除绑定' : '立即绑定' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="info-dialog">
    <t-dialog
      placement="top"
      :header="header"
      confirm-btn="应用"
      cancel-btn="取消"
      :visible="updateUserNameDialog"
      :on-confirm="onDialogConfirm"
      :on-close="closeUserDialog"
      :closeOnOverlayClick="false"
      :width="isMobilePhone ? '90%' : '600'"
    >
      <template v-slot:default>
        <div class="update-name" v-show="isUpdateUser">
          <div class="update-name-content">
            <div class="update-info-input">
              <t-input
                v-if="type === 'nickname'"
                v-model:value="userNickNameValue"
                placeholder="请输入昵称"
                :maxlength="20"
                :clearable="true"
              />
              <t-date-picker
                v-if="type === 'birthday'"
                v-model:value="userBirthday"
                placeholder="请输入生日"
                size="large"
                format="YYYY-MM-DD"
                valueType="YYYY-MM-DD"
                :clearable="true"
                :allowInput="true"
              />
            </div>
          </div>
        </div>
        <div class="img-check" v-show="isUpdateAvatar">
          <div class="img-content">
            <div class="image-viewer__base">
              <img v-if="viewImg" v-lazy="img" alt="图片" class="image-viewer__image" />
              <t-avatar v-else class="upload-img">{{ userNameAvatar }}</t-avatar>
            </div>
            <t-upload
              :beforeUpload="beforeUpload"
              accept=".jpg,.png"
              :sizeLimit="{ size: 1, unit: 'MB', message: '图片大小不超过 1 MB' }"
              :max="1"
              :name="imgName"
              :autoUpload="false"
              action="your_upload_url_here"
            >
              <button class="upload-button">选择文件</button>
            </t-upload>
            <br />
            <div class="avatar-warning">仅支持 1M 以内的 .JPG .PNG 图片格式</div>
          </div>
        </div>
        <div class="bind-mailOrMobile" v-show="isBindMobileOrMail">
          <div class="bind-mail" v-show="!isBindMobile">
            <div class="update-info-input">
              <t-form :data="mailFormDate" ref="mailForm" labelAlign="left" :rules="mailRule">
                <t-form-item label="原邮箱" name="oldEmail" v-show="userEmail">
                  <t-input
                    v-model:value="mailFormDate.oldEmail"
                    placeholder="请输入原邮箱"
                    :clearable="true"
                    name="oldEmail"
                  >
                    <template #prefix-icon> <MailIcon /> </template
                  ></t-input>
                </t-form-item>
                <t-form-item label="绑定邮箱" name="newEmail">
                  <t-input
                    v-model:value="mailFormDate.newEmail"
                    placeholder="请输入绑定邮箱"
                    :clearable="true"
                    name="newEmail"
                    ><template #prefix-icon> <MailIcon /> </template
                  ></t-input>
                </t-form-item>
                <t-form-item label="验证码" name="emailCode">
                  <t-input
                    v-model:value="mailFormDate.emailCode"
                    placeholder="请输入验证码"
                    :clearable="true"
                    :maxlength="6"
                    name="emailCode"
                    ><template #prefix-icon>
                      <MobileVibrateIcon />
                    </template>
                    <template #suffix
                      ><button
                        class="code-btn"
                        @click="handleGetCaptcha('email')"
                        v-bind:disabled="countdown > 0"
                      >
                        {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                      </button></template
                    ></t-input
                  >
                </t-form-item>
              </t-form>
            </div>
          </div>
          <div class="bind-mobile" v-show="isBindMobile">
            <div class="update-info-input">
              <t-form :data="mobileFormDate" ref="mobileForm" labelAlign="left" :rules="mobileRule">
                <t-form-item label="原手机" name="mobile">
                  <t-input
                    v-model:value="mobileFormDate.mobile"
                    placeholder="请输入完整的手机号"
                    :maxlength="11"
                    :clearable="true"
                    v-show="userMobile"
                    name="oldMobile"
                  >
                    <template #prefix-icon>
                      <MobileIcon />
                    </template>
                  </t-input>
                </t-form-item>

                <t-form-item label="绑定手机" name="newMobile">
                  <t-input
                    v-model:value="mobileFormDate.newMobile"
                    placeholder="请输入手机号"
                    :maxlength="11"
                    :clearable="true"
                  >
                    <template #prefix-icon>
                      <MobileIcon />
                    </template>
                  </t-input>
                </t-form-item>

                <t-form-item label="验证码" name="code">
                  <t-input
                    v-model:value="mobileFormDate.code"
                    placeholder="请输入验证码"
                    :maxlength="6"
                    :clearable="true"
                  >
                    <template #prefix-icon>
                      <MobileVibrateIcon />
                    </template>
                    <template #suffix
                      ><button
                        class="code-btn"
                        @click="handleGetCaptcha('mobile')"
                        v-bind:disabled="countdown > 0"
                      >
                        {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                      </button></template
                    >
                  </t-input>
                </t-form-item>
              </t-form>
            </div>
          </div>
        </div>
        <div class="scan-content" v-show="isBindWX">
          <div class="content-wrap">
            <div class="content">
              <img
                v-show="scanStatus === 'noscan'"
                :src="imgSrc"
                alt="scan"
                style="width: 170px; height: 170px"
              />
              <img
                src="../../assets/img/scan_success.svg"
                alt="scan"
                style="width: 170px; height: 170px"
                v-show="scanStatus === 'success'"
              />
              <img
                src="../../assets/img/error.svg"
                alt="scan"
                style="width: 170px; height: 170px"
                v-show="scanStatus === 'error'"
              />
            </div>
            <span class="no_scan" @click="refushGetScanCode()">无法显示二维码？重新获取</span>
          </div>
          <h4>扫码 <strong>关注「vsae 视易」</strong>公众号完成绑定</h4>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup>
import { MailIcon, MobileIcon, MobileVibrateIcon } from 'tdesign-icons-vue-next'
import { useUserStore } from '@/store'
import { MessagePlugin } from 'tdesign-vue-next'
import { updateUserInfo, uploadUserAvatar, checkMobileOrEmail } from '@/api/user'
import { useGlobalStore } from '@/store'
import { getWeChatQrCode } from '@/api/login'
import { copyToClipboard, getUrl, watchIsMobile, checkIsMobile } from '@/utils/util'
const isMobilePhone = ref(checkIsMobile())
const globalStore = useGlobalStore()
const uploadFile = ref(null)
const viewImg = ref(false)
const userStore = useUserStore()
const userInfo = ref(userStore.userInfo)
const userNickNameValue = ref('')
const userEmail = ref('')
const userMobile = ref('')
const userBirthday = ref('')
const userMypromotionCode = ref('')
const userWStatus = ref('')
const imgName = ref('')
const img = ref('')
const updateUserNameDialog = ref(false)
const header = ref('')
const updateMethod = ref(null)
const type = ref('')
const isUpdateUser = ref(false)
const isUpdateAvatar = ref(false)
const isBindMobile = ref(false)
const isBindMobileOrMail = ref(false)
const nickName = ref('')
const mobileForm = ref(null)
const isBindWX = ref(false)
const imgSrc = ref('')
const showExpiredMessage = ref(false)
const wxTicket = ref('')
const socket = ref(null)
const scanStatus = ref('noscan')
const wxButton = ref(false)
const mobileRule = ref({
  newMobile: [
    {
      required: true,
      message: '请输入正确的手机号',
      trigger: 'blur'
    },
    {
      pattern: new RegExp('^1[3456789]\\d{9}$'),
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ]
})
const mobileFormDate = ref({
  mobile: '',
  newMobile: '',
  code: ''
})
const mailFormDate = ref({
  oldEmail: '',
  newEmail: '',
  emailCode: ''
})
const mailRule = ref({
  newEmail: [
    { required: true, message: '邮箱地址必填', trigger: 'blur' },
    {
      pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
})
const mailForm = ref(null)
const onIsMobileChange = newIsMobile => {
  isMobilePhone.value = newIsMobile
}
onMounted(() => {
  const unwatch = watchIsMobile(onIsMobileChange)
  onBeforeUnmount(unwatch)
})
//初始化用户信息
const initializeUserInfo = () => {
  const userInfoParsed =
    typeof userInfo.value === 'string' ? JSON.parse(userInfo.value) : userInfo.value
  userNickNameValue.value = userInfoParsed.name
  userEmail.value = userInfoParsed.email
  userMobile.value = userInfoParsed.mobile
  if (userInfoParsed.birthday) {
    userBirthday.value = userInfoParsed.birthday
  } else {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')

    const formattedDate = `${year}-${month}-${day}` // 拼接为字符串格式 YYYY-MM-DD
    userBirthday.value = formattedDate
  }
  userMypromotionCode.value = userInfoParsed.myPromotionCode
  imgName.value = userInfoParsed.myPromotionCode
  nickName.value = userInfoParsed.name
  ;(mobileFormDate.value.mobile = ''),
    (mobileFormDate.value.newMobile = ''),
    (mobileFormDate.value.code = '')
  if (userInfoParsed.subscribeStatus == 1) {
    userWStatus.value = '已绑定'
    wxButton.value = true
  } else {
    userWStatus.value = ''
  }
}
//用户文字头像
const userNameAvatar = computed(() => userNickNameValue.value.substring(0, 2))

const updateViewImg = () => {
  const userInfoParsed =
    typeof userInfo.value === 'string' ? JSON.parse(userInfo.value) : userInfo.value
  viewImg.value = !!userInfoParsed?.avatar
}

const getImg = () => {
  const userInfoParsed =
    typeof userInfo.value === 'string' ? JSON.parse(userInfo.value) : userInfo.value
  img.value = userInfoParsed?.avatar ?? ''
}

const beforeUpload = file => {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isJPGorPNG) {
    MessagePlugin.error('上传头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt1M) {
    MessagePlugin.error('上传头像图片大小不能超过 1MB!')
    return false
  }

  const reader = new FileReader()
  if (file) {
    reader.readAsDataURL(file.raw)
  }
  reader.onload = () => {
    img.value = reader.result
  }
  uploadFile.value = file.raw
  viewImg.value = true
  return true
}

const userImg = computed(() => {
  const userInfoParsed =
    typeof userInfo.value === 'string' ? JSON.parse(userInfo.value) : userInfo.value
  return userInfoParsed?.avatar
})
const closeUserDialog = () => {
  updateUserNameDialog.value = false
}
const openUpdateNameDialog = methodName => {
  updateUserNameDialog.value = true
  isBindMobileOrMail.value = false
  isBindMobile.value = false
  isUpdateAvatar.value = false
  isUpdateUser.value = false
  updateMethod.value = methodName
  if (methodName === 'updateName') {
    header.value = '修改昵称'
    type.value = 'nickname'
    isUpdateUser.value = true
  } else if (methodName === 'updateBirthday') {
    header.value = '修改生日'
    type.value = 'birthday'
    isUpdateUser.value = true
  } else if (methodName === 'updateAvatar') {
    header.value = '修改头像'
    type.value = 'avatar'
    isUpdateAvatar.value = true
  } else if (methodName === 'updateEmail') {
    header.value = '绑定邮箱'
    type.value = 'email'
    isBindMobileOrMail.value = true
    isBindMobile.value = false
    isBindWX.value = false
  } else if (methodName === 'updateMobile') {
    header.value = '绑定手机'
    type.value = 'mobile'
    isBindMobileOrMail.value = true
    isBindMobile.value = true
    isBindWX.value = false
  } else if (methodName === 'updateWechat') {
    header.value = '绑定微信'
    type.value = 'wechat'
    isBindWX.value = true
    getScanCode()
  }
}

const onDialogConfirm = () => {
  if (updateMethod.value === 'updateName') {
    updateUser({ name: userNickNameValue.value })
  } else if (updateMethod.value === 'updateBirthday') {
    //如果生日不大于18岁,提示错误
    if (new Date().getFullYear() - new Date(userBirthday.value).getFullYear() < 18) {
      MessagePlugin.error('年龄必须大于18岁')
      return
    }
    //如果生日没改变,提示错误
    if (userBirthday.value === userStore.userInfo.birthday) {
      MessagePlugin.error('生日未改变')
      return
    }
    updateUser({ birthday: userBirthday.value })
  } else if (updateMethod.value === 'updateAvatar') {
    //console.log(uploadFile.value)
    updateUser({ avatar: uploadFile.value })
  } else if (updateMethod.value === 'updateEmail') {
    updateUser({ email: mailFormDate.value.newEmail, verCode: mailFormDate.value.emailCode }).then(
      res => {
        if (res.code == 200) {
          MessagePlugin.success('邮箱绑定成功')
        } else {
          MessagePlugin.error(res.error)
        }
      }
    )
  } else if (updateMethod.value === 'updateMobile') {
    updateUser({ mobile: mobileFormDate.value.newMobile, verCode: mobileFormDate.value.code }).then(
      res => {
        if (res.code == 200) {
          MessagePlugin.success('手机绑定成功')
        } else {
          MessagePlugin.error(res.error)
        }
      }
    )
  } else if (updateMethod.value === 'updateWechat') {
    closeUserDialog()
  }
}
//更改用户信息
const updateUser = async params => {
  let result
  //修改生日
  if (params.hasOwnProperty('birthday')) {
    result = await updateUserInfo({ birthday: params.birthday })
    //修改昵称
  } else if (params.hasOwnProperty('name')) {
    result = await updateUserInfo({ name: params.name })
    //修改头像
  } else if (params.hasOwnProperty('avatar')) {
    if (!uploadFile.value) {
      MessagePlugin.error('请选择图片')
      return
    }
    result = await uploadUserAvatar(params.avatar)
  } else if (params.hasOwnProperty('email')) {
    result = await updateUserInfo({ email: params.email, verCode: params.verCode })
  } else if (params.hasOwnProperty('mobile')) {
    result = await updateUserInfo({ mobile: params.mobile, verCode: params.verCode })
  }
  if (result.code === 200) {
    MessagePlugin.success('修改成功')
    closeUserDialog()
    userStore.updateUser(result.data)
    userInfo.value = result.data
    initializeUserInfo()
  } else {
    MessagePlugin.error(result.message)
  }
  updateUserNameDialog.value = false
  isUpdateUser.value = false
  isUpdateAvatar.value = false
  isBindMobileOrMail.value = false
}

const handleGetCaptcha = async type => {
  if (type === 'mobile') {
    if (mobileFormDate.value.newMobile === mobileFormDate.value.mobile) {
      MessagePlugin.error('新手机号不能与旧手机号相同')
      return
    }
    let data = {
      type: 'mobile',
      oldVal: mobileFormDate.value.mobile,
      newVal: mobileFormDate.value.newMobile
    }
    try {
      const res = await checkMobileOrEmail(data)
      if (res.code === 200) {
        globalStore.getCaptcha(mobileFormDate.value.newMobile)
      }
    } catch (error) {
      MessagePlugin.error(error.error)
    }
  }
  if (type === 'email') {
    if (mailFormDate.value.newEmail === mailFormDate.value.oldEmail) {
      MessagePlugin.error('新邮箱不能与旧邮箱相同')
      return
    }
    let data = {
      type: 'email',
      oldVal: mailFormDate.value.oldEmail,
      newVal: mailFormDate.value.newEmail
    }
    try {
      const res = await checkMobileOrEmail(data)
      if (res.code === 200) {
        //console.log(mailFormDate.value.newEmail)
        globalStore.getCaptchaByMail(mailFormDate.value.newEmail)
      }
    } catch (error) {
      MessagePlugin.error(error.error)
    }
  }
}
/**
 * 获取微信二维码
 */
const getScanCode = async () => {
  // 隐藏过期提示
  showExpiredMessage.value = false

  const params = {
    promotionCode: '',
    type: 'bind',
    myPromotionCode: userMypromotionCode.value
  }
  try {
    const { code, data } = await getWeChatQrCode(params)
    if (code !== 200) {
      MessagePlugin.error('获取微信二维码失败')
      return
    }
    const { ticket, image } = data
    wxTicket.value = ticket
    const qrCode = `data:image/jpg;base64,${image}`
    imgSrc.value = qrCode
  } catch (error) {
    //console.log(error)
  }

  // 连接 WebSocket
  connectWebSocket()
}
const removeQRCodeCache = () => {
  cachedData.value = null
}
const connectWebSocket = () => {
  const wsUrl = import.meta.env.VITE_WS_URL + `/login?ticket=${wxTicket.value}`
  socket.value = new WebSocket(wsUrl)
  socket.value.addEventListener('open', () => {})
  socket.value.addEventListener('message', event => handleMessage(event))
  socket.value.addEventListener('close', () => {})
  socket.value.addEventListener('error', error => MessagePlugin.error(error))
}
const handleMessage = event => {
  const data = JSON.parse(event.data)
  // 处理接收到的数据，例如：
  if (data.code === 200) {
    showExpiredMessage.value = true
    removeQRCodeCache()
    MessagePlugin.success('绑定成功')
    updateUserNameDialog.value = false
    isBindWX.value = false
    userStore.refreshUserInfo()
    initializeUserInfo()
  }
  if (data.code === 202) {
    MessagePlugin.success('扫码成功')
    scanStatus.value = 'success'
  } else {
    scanStatus.value = 'error'
    MessagePlugin.error('未知错误')
  }
}
const countdown = computed(() => {
  return globalStore.countdown
})
const refushGetScanCode = () => {
  removeQRCodeCache()
  getScanCode()
}
getImg()
updateViewImg()
initializeUserInfo()
</script>
<style src="./index.scss" scoped></style>
